package com.imooc.controller;

import com.imooc.pojo.Orders;
import com.imooc.pojo.Users;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.service.center.MyOrdersService;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.RedisOperator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.util.UUID;

@Controller
public class BaseController {

    @Autowired
    public MyOrdersService myOrdersService;

    @Autowired
    private RedisOperator redisOperator;

    public static final String FOODIE_SHOPCART = "shopcart";

    public static final Integer COMMENT_PAGE_SIZE = 10;

    public static final Integer PAGE_SIZE = 20;

    public static final String REDIS_USER_TOKEN = "redis_user_token";
    //支付中心调用地址
    String paymentUrl = "http://payment.t.mukewang.com/foodie-payment/payment/createMerchantOrder";

    //微信支付成功->支付中心->天天吃货平台
    //回调通知的url
    //TODO 这里的回调地址我是用内网穿透工具进行对外映射的,这样远程支付中心就能访问我的接口了
    //而且内网穿透工具在项目重启会改变访问路径,相应地址映射代码也要注意修改
    // String payReturnUrl = "http://localhost:8088/orders/notifyMerchantOrderPaid";
    // String payReturnUrl = "http://8ejg65.natappfree.cc/orders/notifyMerchantOrderPaid";
    //这一行注释掉,因为我们在云端服务器或者企业的时候不需要开放这端口,而且写了端口也会用不到nginx,只是调试的时候用,所以我们需要重新打包部署
    // String payReturnUrl = "http://http://api.z.caryguan.work:8088/foodie-dev-api/orders/notifyMerchantOrderPaid";
    String payReturnUrl = "http://http://api.z.caryguan.work/foodie-dev-api/orders/notifyMerchantOrderPaid";

    // 用户上传头像的位置,路径上可以为每个用户增加一个userid,用于区分不同用户的上传
    //这里我们没有写死文件分隔符,因为linux和mac和windows的分隔符有区别,我们可以用File.separator进行代替
    public static final String IMAGE_USER_FACE_LOCATION = File.separator + "workspaces" +
            File.separator + "images" +
            File.separator + "foodie" +
            File.separator + "faces";
//    public static final String IMAGE_USER_FACE_LOCATION = "/workspaces/images/foodie/faces";

    /**
     * 用于检查用户和订单关联是否存在,防止恶意用户请求
     *
     * @return
     */
    public IMOOCJSONResult checkUserOrder(String userId, String orderId) {
        Orders orders = myOrdersService.queryMyOrder(userId, orderId);
        if (orders == null) {
            return IMOOCJSONResult.errorMsg("订单不存在!");
        }
        return IMOOCJSONResult.ok(orders);
    }

    /**
     * @param user
     * @return
     */
    public UsersVO convertUsersVO(Users user) {
        //实现用户的redis会话
        String uniqueToken = UUID.randomUUID().toString().trim();
        redisOperator.set(REDIS_USER_TOKEN + ":" + user.getId(), uniqueToken);

        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user, usersVO);
        //设置token
        usersVO.setUserUniqueToken(uniqueToken);
        return usersVO;
    }
}
